package edu.wpi.cs509.serverlogic;

import java.util.HashMap;

import edu.wpi.cs509.messages.client.MsgLoginReply;
import edu.wpi.cs509.messages.client.MsgLoginReply.LoginResult;
import edu.wpi.cs509.persistence.PersistenceDatabase;
import edu.wpi.cs509.representation.UserAccount;
import edu.wpi.cs509.representation.UserPair;

public class UserDB {
	
	/* Use as a backup just in case the remote mysql server is down */
	private HashMap<String, UserAccount> users =
			new HashMap<String, UserAccount>();
	private boolean usingbackupDB = false;
	
	/**
	 * Creates a storage object for user accounts.
	 */
	public UserDB() {
//		try{
//			PersistenceDatabase.UsernameTaken("user1");
//		} catch(Exception e) {
			usingbackupDB = true;
//		}
		/* If, for whatever reason, we cannot reach external DB, fall back to local */
		if (usingbackupDB == true){
			System.out.println("Falling back to local!");
			UserAccount user1 = new UserAccount("user1", "cs509");
			UserAccount user2 = new UserAccount("user2", "cs509");
			UserAccount user3 = new UserAccount("user3", "cs509");
			
			users.put(user1.getUsername(), user1);
			users.put(user2.getUsername(), user2);
			users.put(user3.getUsername(), user3);
		}else{
			System.out.println("Persistance appears to work, going to use that!");
		}
		/*
		 * CONSTRUCTOR NOT USED ANYMORE user1:cs509 & user2:cs509 already exist in persistant DB!
		 */
	}
	
	/**
	 * Gets the first UserAccount to match the username. - backup function for local DB
	 * 
	 * @param username A unique string for identification
	 * @return         A UserAccount object if found, else null
	 */
	public UserAccount getUserAccount(String username) {
		return users.get(username);
	}
	
	/**
	 * Performs a login using a username and password.
	 * @param pair A username/password combination
	 * @return     A MsgLoginReply.LoginResult constant
	 */
	public MsgLoginReply.LoginResult loginUser(UserPair pair) {
		UserAccount user;
		/*NOTICE: we are now grabbing this value from PersistenceDatabase! */
		if (usingbackupDB == false){
			user = PersistenceDatabase.getUserAccount(pair.getUsername());
		}else {//local backup
			user = this.getUserAccount(pair.getUsername());
		}
		if (user == null) {
			System.err.println("No user: " + pair.getUsername());
			return LoginResult.InvalidCredentials;
		}
		
		if (user.passwordMatch(pair.getPassword())) {
			return LoginResult.LoggedIn;
		}
		
		System.err.println("Invalid password for: " + pair.getUsername());
		return LoginResult.InvalidCredentials;
	}
}
